import { defineStore } from 'pinia'
import { apiURL, apiPostData } from '@/api'
import { baseMd5 } from '@/utils/crypto'

const useAuthStore = defineStore('auth', {
  state: () => ({
    userID: '',
    userName: '',
    userAvatar: '',
    mood: '',
    phone: '',
    token: '',
    level: 0
  }),
  getters: {
    selfPublicInfo(): any {
      return {
        id: this.userID,
        username: this.userName,
        avatar: this.userAvatar,
        mood: this.mood
      }
    },
    isLogin(): boolean {
      return !!this.token
    }
  },
  actions: {
    setUserInfo(data: any = {}) {
      const temp = window.btoa(window.encodeURIComponent(JSON.stringify(data)))
      localStorage.setItem('sghen_user_info', temp)
      this.userID = data.id
      this.userAvatar = data.avatar
      this.userName = data.username || data.name
      this.phone = data.phone
      this.mood = data.mood
      this.token = data.token
      this.level = data.level
    },
    createUser(data: any) {
      data.isCreateUser = true
      return this.login(data)
    },
    login(data: any) {
      return new Promise((resolve, reject) => {
        const func = (_data: any, _resolve: Function, _reject: Function) => {
          const postURL = data.isCreateUser ? apiURL.userCreate : apiURL.login
          apiPostData(postURL, _data)
            .then((resp) => {
              const info = resp.data
              info.expireDuration = data.expireDuration || 24 * 60 * 60
              info.timeLogin = Date.now() / 1000
              this.setUserInfo(info)
              _resolve(resp)
            })
            .catch((err) => {
              _reject(err)
            })
        }
        if (data.pw) {
          data.pw = baseMd5(data.pw)
          if (!data.isCreateUser) {
            data.random = '' + Date.now()
            data.pw = baseMd5(data.pw + data.random)
          }
          func(data, resolve, reject)
        } else {
          func(data, resolve, reject)
        }
      })
    },
    update({ name, avatar, mood }: { name: string; avatar: string; mood: string }) {
      return apiPostData(apiURL.userUpdate, { name, avatar, mood }).then(() => {
        const temp = localStorage.getItem('sghen_user_info')
        if (temp) {
          const info = JSON.parse(window.decodeURIComponent(window.atob(temp)))
          info.username = name
          info.avatar = avatar
          info.mood = mood
          this.setUserInfo(info)
        }
      })
    },
    logout() {
      this.setUserInfo()
    }
  }
})

export const initUserInfo = function () {
  const temp = localStorage.getItem('sghen_user_info')
  if (!temp) {
    return
  }

  const userInfo = JSON.parse(window.decodeURIComponent(window.atob(temp)))
  const expireDuration = userInfo.expireDuration || 0
  const timeLogin = userInfo.timeLogin || 0
  const duration = Date.now() / 1000 - timeLogin
  if (duration > expireDuration * 0.95) {
    // 取个0.95阈值，超过则认为已过有效期
    return
  }

  const authStore = useAuthStore()
  authStore.setUserInfo(userInfo)
}

export default useAuthStore
